#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
using namespace std;

int main(){
  pid_t id = fork();
  if(id < 0)
  {
    perror("fork");
    exit(10);
  }
  else if(id == 0)
  {
    int cnt = 3;
    while(cnt){
      cout << "I'm child process!";
      cout << " pid:" << getpid();
      cout << " ppid:" << getppid();
      cout << "  " << cnt+1 << endl;
      sleep(1);
      //cnt/=0;
      //int *p = NULL;
      //*p = 100;
    }
    exit(122);
  }
  else{
    //父进程等待回收子进程
    //wait
    //sleep(5);
    //pid_t ret = wait(nullptr); 
    //if(ret > 0)
    //{
    //  cout << "等待子进程成功！ret:" << ret << endl;
    //}
    
    //waitpid
    //sleep(5);
    //int status = 0;
    //pid_t ret = waitpid(id, &status, 0); 
    //if(ret > 0)
    //{
    //  cout << "等待子进程成功！ret:" << ret;
    //  cout << " status:" << status << endl;
    //  //cout << " exit_code:" << ((status>>8)&0xFF) << endl;
    //}
    sleep(5);
    int status = 0;
    pid_t ret = waitpid(id, &status, 0); 
    if(ret > 0)
    {
      cout << "等待子进程成功！ret:" << ret;
      cout << " SIGNUM:" << (status&0x7F);
      cout << " ExitCode:" << ((status>>8)&0xFF) << endl;
    }
    while(1){
      cout << "I'm father process!";
      cout << " pid:" << getpid();
      cout << " ppid:" << getppid() << endl;
      sleep(1);
    }
  }
}
